package com.leetcodehot.problems;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class problems501 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    private class Node {
        int val;
        int count;

        public Node(int val, int count) {
            this.val = val;
            this.count = count;
        }
    }

    private Map<Integer, Node> map = new TreeMap<>();

    private int max = Integer.MIN_VALUE;

    public int[] findMode(TreeNode root) {
        dfs(root);
        List<Integer> result = new ArrayList<Integer>();

        for (Node node : map.values()) {
            if (node.count == max) {
                result.add(node.val);
            }
        }
        int[] res = new int[result.size()];
        for (int i = 0; i < result.size(); i++) {
            res[i] = result.get(i);
        }

        return res;
    }

    private void dfs(TreeNode root) {
        if (root == null) return;
        dfs(root.left);
        Node orDefault = map.getOrDefault(root.val, new Node(root.val, 0));
        orDefault.count++;
        max = Math.max(max, orDefault.count);
        map.put(root.val, orDefault);
        dfs(root.right);
    }

    /**
     * 下面是最优写法，结合了中序递增的特点，以及用少量的内存实现
     */
    /*
    ArrayList<Integer> result;
    int maxCount;
    int count;
    TreeNode pre;
    public int[] findMode(TreeNode root) {
        result = new ArrayList<>();
        maxCount = 0;
        count = 0;
        pre = null;
        findModeHelper(root);
        int[] res = new int[result.size()];
        for(int i = 0; i < res.length; ++i){
            res[i] = result.get(i);
        }
        return res;

    }

    private void findModeHelper(TreeNode cur){
        if(cur == null){
            return;
        }

        //左
        findModeHelper(cur.left);
        //中
        if(pre == null){
            count = 1;
        }else if(cur.val == pre.val){
            count++;
        }else{
            count = 1;
        }
        pre = cur;
        if(count == maxCount){
            result.add(cur.val);
        }
        if(count > maxCount){
            maxCount = count;
            result.clear();
            result.add(cur.val);
        }
        //右
        findModeHelper(cur.right);
    }*/
}
